<?php

namespace yan\backendclient\modules\backendmodule\models;

use Yii;

use yan\backendclient\LoadConfig;
/**
 * This is the model class for table "{{%backend_module}}".
 *
 * @property integer $id
 * @property string $module_id
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class BackendModule extends \yii\db\ActiveRecord
{
    const INSTALL = 1; //已安裝;
    const UNINSTALL = -1;//未安裝
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%backend_module}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['module_id'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['module_id', 'targetClass', 'name'], 'string', 'max' => 255],
            [['description'], 'safe'],
            // [['module_id'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('debug', 'ID'),
            'module_id' => Yii::t('debug', 'Module ID'),
            'targetClass'=>Yii::t('debug', 'Target Class'),
            'status' => Yii::t('debug', 'Status'),
            'name' => Yii::t('debug', 'Name'),
            'description' => Yii::t('debug', 'Description'),
            'created_at' => Yii::t('debug', 'Created At'),
            'updated_at' => Yii::t('debug', 'Updated At'),
        ];
    }

    public function behaviors()
    {

        $data = \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ]);
        return $data;
    }
    
    
    // 獲取modules的安裝列表
    public function listModules(){
        $loadConfig = new LoadConfig(Yii::getAlias('@backend'));
        $list = $loadConfig->getModules();
        $data = [];
        if(!empty($list)){
            $modules = static::find()->asArray()->all();
            $modules = \yii\helpers\ArrayHelper::index($modules, 'module_id');
            foreach ($list as $key => $val) {
                if($key=='backendmenu') continue;
                $module = Yii::$app->getModule($key); // ==  $val['class']::getInstance();
                
                if(!empty($module)){
                    $moduleModle = isset($modules[$key]) ? $modules[$key] : [];
                    $data[] = [
                        'id'=>$key,
                        'name' => isset($module->moduleName) ? $module->moduleName : '',
                        'description' => isset($module->moduleDescription) ? $module->moduleDescription : '',
                        'flag' => !empty($moduleModle) ? static::INSTALL : static::UNINSTALL,
                        'flagActive' => !empty($moduleModle) ? $moduleModle['status'] : '',
                    ];
                }
            }
        }
        return $data;
    }

    // 安装
    public function installDo($module_id){
        $flag = true;

        // 获取module入口 
        $module = Yii::$app->getModule($module_id);

        if(!empty($module)){
            $model = new static;
            $model->loadDefaultValues();
            $model->module_id = $module_id;
            $model->name = $module->moduleName;
            $model->description = $module->moduleDescription;

            if($module->installDo($module_id, BackendModuleSql::className())){
                $flag = $model->save();
            }
        }
        return $flag;
    }


    // 卸载
    public function uninstallDo($module_id){
        $flag = true;
        // 获取module入口 
        $module = Yii::$app->getModule($module_id);

        if(!empty($module)){
            $model = static::find()->where(['module_id'=>$module_id])->one();
            
            if($module->uninstallDo($module_id)){
                if(!empty($module_id)){
                    $flag = $model->delete();
                    BackendModuleSql::deleteAll(['module_id'=>$module_id]);
                }
                    

            }
        }
        return $flag;
    }

    // 删除
    public function removeDo($module_id){
        $model = static::find()->where(['module_id'=>$module_id])->one();
        
        if(!empty($model)){
            return false;
        }
        $path = Yii::$app->basePath . DS . 'modules' . DS . $module_id;

        $loadConfig = new LoadConfig;
        $loadConfig->deltree($path);
        return @rmdir($path);
    }

    // 启用停用
    public function activeDo($module_id){
        $flag = false;
        $model = static::find()->where(['module_id'=>$module_id])->one();
        if(!empty($model)){
            $model->status = $model->status == 1 ? 0 : 1;
            $flag = $model->save();
        }
        return $flag;
    }

    public function getSqlList($module_id){
        $path = Yii::getAlias('@backend') . DS . 'modules' . DS . $module_id . DS . 'data';
        $flag = !empty($targetClass) && class_exists($targetClass) ? true : false;
    	$list = [];
        if( file_exists($path) ){
    		$dp = dir($path);

    		while($file=$dp->read()){

                if($file!='.'&& $file!='..'){
                	$file = $path . DS . $file;
                	// 当为文件不是目录时
                	if( is_file($file) ){
                		// 获取文件名，然后格式化成CLASS名
                		$root_url = dirname(Yii::$app->basePath);
                		$class = str_replace([$root_url,'.php'], '' ,$file);
                		
                        $class = str_replace('/', '\\', $class);

                		if(class_exists($class)){
                			$classModel = new $class;
                			if(is_subclass_of($classModel, 'yii\db\Migration')){                				
                				$list[$class] = $class;
                			}
                		}
                	}
                }
            }
    	}
        return $list;        
    }
    public function tableDo($type, $module_id, $targetClass){
        if($type=='up'){
            $classModel = new $targetClass;
            if(is_subclass_of($classModel, 'yii\db\Migration')){
                try {                					
                    // 判断是否数据表中存在
                    $flagHas = BackendModuleSql::find()->where(['module_id'=>$module_id, 'targetClass'=>$targetClass])->exists();
                    // 不存在就添加
                    if( !$flagHas ){
                        $classModel->up();
                        $sqlClass = new BackendModuleSql;
                        $sqlClass->loadDefaultValues();
                        $sqlClass->module_id = $module_id;
                        $sqlClass->targetClass = $targetClass;
                        if(!$sqlClass->save()){
                            throw new \Exception(\yii\helpers\Json::encode($sqlClass->getErrors()), 5003);                            
                        }
                    }
                } catch (\Exception $e) {
                    throw new \Exception($e->getMessage(), 5003);									
                }                
            }
        }elseif($type=='down'){
            $classModel = new $targetClass;
            if(is_subclass_of($classModel, 'yii\db\Migration')){
                try {
                    $classModel->down();
                    BackendModuleSql::deleteAll(['module_id'=>$module_id, 'targetClass'=>$targetClass]);
                } catch (\Exception $e) {
                    throw new \Exception($e->getMessage(), 5003);	
                }                
            }
        }
        return true;
    }
}
